package utils;

import org.apache.commons.lang.StringUtils;

import java.util.UUID;

/**
 * @author zhangzc
 * @since 2017/10/31
 */
public class UUIDUtils {

    /**
     * 获取UUID
     *
     * @return
     */
    public static String getUUID() {
        return UUID.randomUUID().toString();
    }

    /**
     * 获取指定长度的UUID
     *
     * @param index
     * @return
     */
    public static String getUUID(int index) {
        String uuid = UUID.randomUUID().toString();
        uuid = StringUtils.replace(uuid, "-", "");
        return uuid.substring(0, index);
    }

    /**
     * 获取数字UUID
     *
     * @return
     */
    public static String getNumUUID() {
        String uuid = UUID.randomUUID().toString();
        uuid = StringUtils.replace(uuid, "-", "");
        String result = "";
        if (uuid != null && !uuid.equals("")) {
            for (int i = 0; i < uuid.length(); i += 4) {
                result += Integer.valueOf(uuid.substring(i, 4 + i), 16);
            }
        }
        return result;
    }

    /**
     * 获取指定长度的数字UUID
     *
     * @param index
     * @return
     */
    public static String getNumUUID(int index) {
        return getNumUUID().substring(0, index);
    }

    /**
     * uuid转换数字
     * ***注意下标越界
     * @param uuid
     * @return
     */
    public static String generateNumber(String uuid, int startIndex, int length) {
        //String uuid = UUID.randomUUID().toString();
        uuid = StringUtils.replace(uuid, "-", "");
        String result = "";
        if (uuid != null && !uuid.equals("")) {
            for (int i = 0; i < uuid.length(); i += 4) {
                result += Integer.valueOf(uuid.substring(i, 4 + i), 16);
            }
        }
        return result.substring(startIndex, startIndex+length);
    }
}
